import React, { useState, useEffect } from 'react'
import { TreeSelect } from 'antd';
import { axiosConfig, backIP } from '../common/config';
import axios from 'axios'
import { getToken } from '../common/util';

export default function Header({ setHouseID, setFloor }) {
    const [selectValue, setSelectValue] = useState(undefined);
    const [treeData, setTreeData] = useState([])

    const onChange = (value: string) => {
        const carryArr = value.split('-')
        const houseID = carryArr[0];
        const floor = carryArr[1]
        setHouseID(parseInt(houseID))
        setFloor(parseInt(floor))
        setSelectValue(value)
    };

    const generateArray = (arrayNum: number, parentID: number, houseName: string): any[] => {
        const arr = [];
        for (let index = 0; index < arrayNum; index++) {
            arr.push({
                title: `${houseName}-${index + 1}层`,
                value: `${parentID}-${index + 1}`
            })
        }
        return arr;
    }

    // 获取数据库中的楼和楼层信息，并且将
    const getHouseFloorData = async () => {
        const token: string = getToken();
        const { data: res }: { data: axiosConfig } = await axios.get(`${backIP}/floor`, {
            headers: {
                Authorization: token,
            }
        })
        const treeData = res.data.map(item => {
            return {
                title: item.value,
                value: item.id,
                disabled: true,
                children: generateArray((item.floor_number as number), item.id, item.value)
            }
        })
        setTreeData(treeData)

    }

    useEffect(() => {
        getHouseFloorData()
    }, [])

    return (
        <TreeSelect
            style={{ width: '100%' }}
            value={selectValue}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={treeData}
            placeholder="请选择楼和楼层"
            onChange={onChange}
        />
    )
}
